package com.xuyuan.concurrent.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Task implements Runnable {
    private CyclicBarrier barrier;

    public Task(CyclicBarrier barrier) {
        this.barrier = barrier;
    }

    @Override
    public void run() {
        try {
            System.out.println("Thread " + Thread.currentThread().getId() + " starts executing the task");
          
            // 执行任务的代码
            Thread.sleep(1000); // 模拟任务执行时间
          
            System.out.println("Thread " + Thread.currentThread().getId() + " finishes the task and waits at the barrier");
          
            barrier.await(); // 等待所有线程到达屏障点
      
            System.out.println("All threads have reached the barrier, continue with the next step");
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Task task = new Task(new CyclicBarrier(2));
        for (int i=0;i<3;i++){
            executorService.submit(()->task.run());
        }
    }
}